package top.sdwu_top.kbase.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import top.sdwu_top.kbase.common.annocation.CurrentUser;
import top.sdwu_top.kbase.common.model.Wrapper;
import top.sdwu_top.kbase.dto.ChangePasswordDto;
import top.sdwu_top.kbase.dto.KbaseAuthUserDto;
import top.sdwu_top.kbase.entity.KbaseAuthUser;
import top.sdwu_top.kbase.service.IKbaseAuthUserService;
import top.sdwu_top.kbase.vo.KbaseAuthUserVo;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhipeng.duan@nvr-china.com
 * @since 2020-02-20
 */
@RestController
@RequestMapping("api/user")
public class KbaseAuthUserController {

    @Autowired
    IKbaseAuthUserService userService;

    @GetMapping
    public Wrapper<KbaseAuthUserDto> getNowUser(@CurrentUser KbaseAuthUser user) {
        return Wrapper.ok(userService.getCurrentUser(user));
    }

    @PostMapping("page")
    public Wrapper<Page<KbaseAuthUserDto>> getPage(@CurrentUser KbaseAuthUser user, @RequestBody KbaseAuthUserVo userVo) {
        return Wrapper.ok(userService.page(user, userVo));
    }

    @DeleteMapping("{id}")
    public Wrapper<String> delete(@CurrentUser KbaseAuthUser user, @PathVariable("id") String id) {
        if (userService.delete(user, id)) {
            return Wrapper.ok("删除用户成功");
        }
        return Wrapper.error("删除用户失败");
    }

    @PostMapping
    public Wrapper<String> create(@CurrentUser KbaseAuthUser currentUser, @RequestBody KbaseAuthUser user) {
        if (userService.save(currentUser, user)) {
            return Wrapper.ok(user.getSsn() + "用户新增成功");
        }
        return Wrapper.error(user.getSsn() + "用户新增失败");
    }

    @GetMapping("{id}")
    public Wrapper<KbaseAuthUserDto> get(@CurrentUser KbaseAuthUser user,@PathVariable("id") String id) {
        return Wrapper.ok(userService.getUserById(user, id));
    }

    @PutMapping
    public Wrapper<String> update(@CurrentUser KbaseAuthUser currentUser, @RequestBody KbaseAuthUser user) {
        if(userService.update(currentUser, user)) {
            return Wrapper.ok("用户更新成功");
        }
        return Wrapper.error("用户更新失败");
    }

    @PostMapping("password")
    public Wrapper<String> changePassword(@CurrentUser KbaseAuthUser user, @RequestBody ChangePasswordDto passwordDto) {
        if (userService.changePassword(user, passwordDto)) {
            return Wrapper.ok("密码修改成功");
        }
        return Wrapper.error("密码修改失败");
    }

    @PutMapping("current")
    public Wrapper<String> updateNowUser(@CurrentUser KbaseAuthUser currentUser, @RequestBody KbaseAuthUser user) {
        if (userService.updateNowUser(currentUser, user)) {
            return Wrapper.ok("用户信息修改成功");
        }
        return Wrapper.error("用户信息修改失败");
    }

}

